<script setup>
import { ref, defineProps, defineEmits, onMounted ,computed} from 'vue'
import { useRouter } from 'vue-router'
import { formatDate, getFourDays } from '@/utils/index.js'
import { showToast } from 'vant';
import api from "@/api/index.js";


const router = useRouter()
const emit = defineEmits(['closePopup'])
const props = defineProps({
  scenicDetail: Object,
  voteDetail: Object,
  showPopup: Boolean,
  goodsKindsInfolist: Object,
  sessionlist: Object,
  dateInfoArraylist: Object,
  scenicId: String,
  sortid: String,
  marketPrice: Number,
  productId:String,
  itemVoteDetail: Object
})

const voteInfo = ref(null)

const minDate = ref(null)
const maxDate = ref(null)
const initDate = () => {
  minDate.value = new Date()
  const currentDate = new Date()
  const thirtyDaysLater = new Date(currentDate)
  thirtyDaysLater.setDate(currentDate.getDate() + 30)
  maxDate.value = thirtyDaysLater
}

const stepperMax = ref(99)
const _getPandaScenicVoteDetail = (id = props.productId, first) => {
  initDate()
  api.getPandaScenicVoteDetail(id).then((res) => {
    res.data.peopleGroupStr = props.voteDetail.peopleGroupStr
    voteInfo.value = res.data
    localStorage.setItem('ticketTypesDetail', JSON.stringify({ ...props.itemVoteDetail, ...res.data }))
    if (res.data.sellStartTime) {
      minDate.value = new Date(res.data.sellStartTime)
    }
    if (res.data.sellEndTime) {
      maxDate.value = new Date(res.data.sellEndTime)
    }
    if (res.data?.limited) {
      stepperMax.value = res.data.limited
    }
    if (first) {
      setTimeout(() => {
        scroll()
      })
    }
  })
}
_getPandaScenicVoteDetail(props.productId, true)
const number = ref(1)
const price = ref(props.marketPrice)
const allPrice = ref(price.value )
const showTime = ref(false)
const moreTimeClick = () => {
  showTime.value = true
}

const numberChange = (number) => {
  allPrice.value = (price.value * 10000) * number / 10000
}
const ticketTypes = ref(0)
const ticketTypesClick = (key,item) => {
  _getPandaScenicVoteDetail(item.id)
  price.value=item.unitPriceStandard
  ticketTypes.value = key
  allPrice.value = (item.unitPriceStandard * 10000) * number.value / 10000
}

const session = ref(0)
const sessionClick = (key) => {
  session.value = key
}

const timeList = ref(getFourDays())
const timeKey = ref('')
const timeKeyDate = computed(() => new Date(timeKey.value)); // 将日期字符串转换为日期对象
const timeChangeClick = (key) => {
  timeKey.value = key
}
onMounted(() => {
  if (timeList.value.length > 0 ) {
    timeChangeClick(timeList.value[0].yearTime)
  }
  if (props.sessionlist.length > 0) {
    session.value = props.sessionlist[0].id
  }
  if ( props.productId.length > 0) {
    ticketTypes.value = props.productId
  }
})
const scroll = () => {
  const targetElement = document.getElementsByClassName('action_button')[0]
  targetElement.scrollIntoView({ behavior: 'smooth' })
}

const selectChange = (data) => {
  const time = formatDate(data)
  const repeat = timeList.value.some((item) => {
    return item.yearTime === time.yearTime
  })
  if (!repeat) {
    const len = timeList.value.length
    timeList.value[len - 1] = time
  }
  timeKey.value = time.yearTime
  showTime.value = false
}

const bookClick = () => {
  localStorage.setItem('scenicDetail', JSON.stringify(props.scenicDetail))
  if (!ticketTypes.value) {
    showToast("未选择种类")
  } else if (!timeKey.value) {
    showToast("未选择日期")
  } else {
    router.push({path: '/pandaScenicOrder', query: {
        bookDate: timeKey.value,
        vanum: number.value,
        productid: ticketTypes.value, //商品id
        sessionid: session.value, //场次id
      }
    })
  }
}

const useOpenAndClose = () => {
  const closeCalendarClick = () => {
    showTime.value = false
  }

  const closeBookPopup = () => {
    if (showTime.value) {
      showTime.value = false
    } else {
      emit('closePopup')
    }
  }
  return { closeCalendarClick, closeBookPopup }
}

const { closeCalendarClick, closeBookPopup } = useOpenAndClose()
</script>
<template>
  <van-popup
    teleport="body"
    class="van_popup"
    :style="{ 'max-height': '70vh' }"
    v-model:show="props.showPopup"
    round
    position="bottom"
    @click-overlay="closeBookPopup"
  >
    <div class="box" v-show="!showTime">
      <div class="header">
        <div class="name">{{ voteDetail.peopleGroupStr }}</div>
        <img @click="closeBookPopup" class="close" src="@/assets/images/icons/close-666666.png" alt="">
      </div>
      <div class="content">
        <div class="content_top">
          <div class="type">
            <div class="name">门票种类</div>
            <div class="button_list">
              <div v-for="item in voteDetail.list" :key="item.id" @click="ticketTypesClick(item.id, item)" class="button"
                   :class="{ 'action_button': ticketTypes === item.id }">
                {{ item.ticketName }}
              </div>
            </div>
          </div>
          <div class="type" v-if="voteInfo?.scenesInfos.length">
            <div class="name">场次</div>
            <div class="button_list">
              <div
                v-for="item in voteInfo.scenesInfos"
                :key="item.id" @click="sessionClick(item.id)"
                class="button"
                :class="{ 'action_button': session === item.id }"
              >
                {{ item.beginTime }}-{{ item.endTime }}
              </div>
            </div>
          </div>
          <div class="time">
            <div class="name">使用日期</div>
            <div class="time_list">
              <div @click="timeChangeClick(item.yearTime)" v-for="item in timeList" :key="item.yearTime" class="time_button"
                   :class="{ 'time_button_action': timeKey === item.yearTime }">
                <div class="top">{{ item.name }}</div>
                <div class="bottom">{{ item.time }}</div>
              </div>

              <div class="time_button more" @click="moreTimeClick">
                <div class="top">更多</div>
                <div class="bottom">日期</div>
              </div>
            </div>
          </div>
          <div class="number">
            <div class="name">购买数量</div>
            <van-stepper :max="stepperMax" @change="numberChange" v-model="number" integer />
          </div>
        </div>
      </div>
      <div class="popup_bottom">
        <div class="button_box">
          <div class="book_button" @click="bookClick">预订</div>
          <div class="price">
            <span class="icon">￥</span>
            <span class="price_number">{{ allPrice }}</span>
          </div>
          <div class="text">应付金额：</div>
        </div>
      </div>
    </div>
    <div class="calendar_box" v-show="showTime">
      <div class="header">
        <div class="name">使用日期</div>
        <img @click="closeCalendarClick" class="close" src="@/assets/images/icons/close-666666.png" alt="">
      </div>
      <van-calendar
        :default-date="timeKeyDate"
        :show-title="false"
        :show-subtitle="false"
        v-show="showTime"
        :poppable="false"
        :show-confirm="false"
        :style="{ maxHeight: 'calc(70vh - 6.3rem)' }"
        :min-date="minDate"
        :max-date="maxDate"
        row-height="4rem" @select="selectChange"
      />
    </div>
  </van-popup>
</template>

<style scoped lang="scss">
@mixin header {
  height: 2.8rem;
  margin-top: 2rem;
  justify-content: space-between;
  display: flex;
  margin-bottom: 1.5rem;

  .name {
    font-size: 2rem;
    font-weight: bold;
    color: #2F3836;

  }

  .close {
    width: 1.6rem;
    height: 1.6rem;
  }
}
.box {
  padding: 0 2rem;
  display: flex;
  flex-direction: column;

  .header {
    height: 2.8rem;
    margin-top: 2rem;
    justify-content: space-between;
    display: flex;
    margin-bottom: 1.5rem;

    .name {
      font-size: 2rem;
      font-weight: bold;
      color: #2F3836;

    }

    .close {
      width: 1.6rem;
      height: 1.6rem;
    }
  }

  .content{
    max-height: calc(70vh - 2rem - 2.8rem - 1.5rem - 9rem);
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    .content_top{
      padding-top: .5rem;
      flex: 1;
    }
  }
  .popup_bottom {
    flex-shrink: 0;
    height: 9rem;
    .button_box{
      padding-top: 1rem;
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
      .book_button {
        height: 3.8rem;
        line-height: 3.8rem;
        background: var(--van-primary-color);
        border-radius: .5rem;
        font-size: 1.6rem;
        color: #FFFFFF;
        padding: 0 3rem;
        margin-left: 1rem;
      }

      .book_button:active {
        background: #4b947f;
      }

      .price {
        color: #ED6316;

        .icon {
          font-size: 1.4rem;
        }

        .price_number {
          font-size: 2.2rem;
        }
      }

      .text {
        font-size: 1.4rem;
        color: #999999;
      }
    }
  }

  .type {
    margin-bottom: 2rem;

    .name {
      font-size: 1.4rem;
      color: #999999;
      line-height: 1.6rem;
      margin-bottom: 1rem;
    }

    .button_list {
      display: flex;
      flex-wrap: wrap;

      .button {
        background: rgba(0, 0, 0, 0.05);
        line-height: 2rem;
        border-radius: .5rem;
        font-size: 1.4rem;
        color: #666666;
        text-align: center;
        padding: .5rem 1.5rem;
        margin-right: 1rem;
        margin-bottom: 1.5rem;
        white-space:nowrap;
        overflow:hidden;
        text-overflow:ellipsis;
      }

      .action_button {
        color: #FFFFFF;
        background: var(--van-primary-color);
      }
    }
  }

  .time {
    .name {
      font-size: 1.4rem;
      color: #999999;
      line-height: 1.6rem;
      margin-bottom: 1rem;
    }

    .time_list {
      display: flex;
      justify-content: space-between;
      padding-bottom: 2rem;
      border-bottom: .1rem solid #EEEEEE;

      .time_button {
        width: 6.5rem;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        height: 5.1rem;
        background: rgba(0, 0, 0, 0.05);
        border-radius: .5rem;
        font-size: 1.2rem;
        color: #666666;

        .top {
          margin-bottom: .3rem;
        }

        .button {
          margin-top: .3rem;
        }
      }

      .time_button_action {
        background-color: Var(--van-primary-color);
        color: #FFFFFF;
      }

      .time_button_disabled {
        color: #BBBBBB;
      }

      .more {
        color: var(--van-primary-color);
        width: 5.4rem;
      }
    }
  }

  .number {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 2rem;
    margin-bottom: 4rem;

    .name {
      font-size: 1.4rem;
      color: #999999;
    }
  }

}

.calendar_box{
  .header{
    @include header;
    padding: 0 2rem;
  }
}
</style>